import tool from '../modules/tool'
import store from '../modules/store'
let tasks = []

export default {
  printing: false,
  async add(order) {
    tasks.push(order)
    this.runner()
    await tool.wait(0.2)
    this.runner()
  },
  async runner() {
    let start = true
    await tool.wait(0.1)
    if (this.printing) return
    let count = 0
    let timer = setInterval(() => {
      if (store.getItem('printerStatus')) {
        // store.setItem('printerStatus', undefined)
      } else {
        store.setItem('printerStatus', true)
      }
    }, 1000);
    this.printing = true
    while (1) {
      if (!tasks.length) {
        this.printing = false
        clearInterval(timer)
        store.setItem('printerStatusText', '')
        store.setItem('printerStatus', undefined)
        return
      }
      count++
      store.setItem('printerStatusText', `正在尝试打印，已发送${count}，剩余${tasks.length}`)
      tool.connectAndPrintLabel(tasks[0])
      tasks = tasks.slice(1)
      if (!tasks.length) {
        this.printing = false
        clearInterval(timer)
        store.setItem('printerStatusText', '')
        store.setItem('printerStatus', undefined)
        return
      }
      if (start) {
        start = false
        await tool.wait(2)
      }
      await tool.wait(3)
    }
  }
}